package com.imagepreview.plugin;

import android.content.Context;
import android.content.Intent;

import androidx.annotation.NonNull;

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.embedding.engine.FlutterEngineCache;
import io.flutter.embedding.engine.dart.DartExecutor;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugins.GeneratedPluginRegistrant;

/**
 * 引擎sdk
 */
public class FlutterEngineDelegate {

    private static FlutterEngineDelegate instance = new FlutterEngineDelegate();
    private static final String CHANNEL = "com.example.android_native_with_flutter/route";

    private Context context;
    private MethodChannel channel;

    public static FlutterEngineDelegate getInstance() {
        return instance;
    }

    private FlutterEngineDelegate() {
    }

    public void init(Context context) {
        this.context = context;
        FlutterEngine flutterEngine = new FlutterEngine(context);
        GeneratedPluginRegistrant.registerWith(flutterEngine);
//        flutterEngine.getDartExecutor().executeDartEntrypoint(
//                DartExecutor.DartEntrypoint.createDefault()
//        );

        FlutterEngineCache.getInstance().put("cached_engine", flutterEngine);
        channel = new MethodChannel(
                flutterEngine.getDartExecutor().getBinaryMessenger(),
                CHANNEL
        );
    }

    public static final String ROUTE_PATH = "routePath";

    public static Intent createIntent(@NonNull Context context, @NonNull String routePath) {
        FlutterEngine flutterEngine = FlutterEngineCache.getInstance().get("cached_engine");
        if (flutterEngine == null) {
            throw new RuntimeException("FlutterEngine is null");
        }
        if (!flutterEngine.getDartExecutor().isExecutingDart()) {
            flutterEngine.getDartExecutor().executeDartEntrypoint(
                    DartExecutor.DartEntrypoint.createDefault()
            );
        }
        FlutterEngineDelegate.getInstance().setInitialRoute(routePath);
        Intent intent = FlutterActivity.withCachedEngine("cached_engine")
                .build(context);
        intent.putExtra(ROUTE_PATH, routePath);
        return intent;
    }

    private void setInitialRoute(@NonNull String route) {
        channel.invokeMethod("setInitialRoute", route);
    }
}
